package com.sux.demo;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class HeartbeatThread extends Thread {
    private ChannelGroup channelGroup;
    private boolean running = true;

    public HeartbeatThread(Channel channel) {
        channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        channelGroup.add(channel);
    }

    public HeartbeatThread(ChannelGroup channelGroup) {
        this.channelGroup = channelGroup;
    }

    @Override
    public void run() {
        while (running) {
            try {
                if (channelGroup.size() > 0) {
                    System.out.println("发送心跳");
                    for (Channel channel : channelGroup) {
                        channel.writeAndFlush(new PingWebSocketFrame());
                    }
                }

                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void close() {
        running = false;
    }
}
